package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.impl.AccountServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UserLoginServlet extends HttpServlet {
    private static final String SIGNON_FORM = "/WEB-INF/jsp/account/SignonForm.jsp";
    public static final String MAIN = "/WEB-INF/jsp/catalog/Main.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(SIGNON_FORM).forward(req, resp);//跳转到登录界面
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain");
        PrintWriter out = resp.getWriter();

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String verifyCode = req.getParameter("verifyCode");

        String sessionCacheData = (String) req.getSession().getAttribute("cacheData");
        if(sessionCacheData == null){
            out.print("errorServlet");
            return;
        }

        if(! sessionCacheData.equalsIgnoreCase(verifyCode)){
            out.print("errorVerifyCode");
            return;
        }

        AccountService accountService = new AccountServiceImpl();

        if(accountService.login(username, password) == null){
            out.print("errorAccount");
        }
        else{
            Account account = accountService.getAccountByUsername(username);//获取完整用户信息
            account.setAuthenticated(true);//授权
            req.getSession().setAttribute("account", account);//设置会话信息
            out.print("ok");
        }
    }
}
